import axios from 'axios'
import { getToken } from '@/utils/auth'
import store from '@/store'

function hasObj(data) {
  let flag = false
  for (let k in data) {
    if (data[k] && Object.prototype.toString.call(data[k]) === '[object Object]') {
      flag = true
      break
    }
  }
  return flag
}

/*
 * 接口请求
 * @param {Boolean} options.showLoading 是否显示loading modal 默认false
 * 如果本地联调需要修改 baseURL, 在提交到远程仓库之前，还原回去，不要把联调的地址提交上去了
 */
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url
  // baseURL: 'http://xs.zjpowerhealth.cn:8018/mbgl',
  withCredentials: true, // 在跨域请求时发送cookie
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  // 修改请求数据
  transformRequest: [
    function(data) {
      if (hasObj(data)) {
        return JSON.stringify(data)
      }
      let ret = ''
      for (const it in data) {
        // 去除空字符串的请求字段
        if (data[it] !== '') {
          if (ret !== '') ret += '&'
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
        }
      }
      return ret
    }
  ],
  timeout: 60000
})
// eslint-disable-next-line no-proto
// service.__proto__ = axios

/**
 * @description 请求发起前的拦截器
 * @returns {AxiosRequestConfig} config
 */
service.interceptors.request.use(
  (config) => {
    console.log(store.state.remoteUrl)
    config.url = store.state.remoteUrl + config.url
    if (getToken()) {
      config.headers['ut'] = getToken()
      config.headers['st'] = 3 // 用户信息获取  暂时写死
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

/**
 * @description 响应收到后的拦截器
 * @returns {}
 */
service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code === '401') {
      return Promise.reject(new Error(res.message || 'Error'))
    } else if (res.code * 1 !== 1 && res.code !== '80034') {
      if (response.config.responseType === 'arraybuffer') return response
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return response
    }
  },
  (error) => {
    if (error.response) {
      const { status } = error.response
      if (status === 401) {
        return Promise.reject(new Error(error.message || 'Error'))
      } else {
        return Promise.reject(error)
      }
    } else {
      return Promise.reject(error)
    }
  }
)

export default service
